package top.csmcool.musicapi.client;

/*
 * @description
 * @date 2025/1/29
 * @author shijin
 * @version 1.0
 */

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import top.csmcool.musicapi.config.SystemProperties;
import top.csmcool.musicapi.domain.Users;
import top.csmcool.musicapi.enums.StatusCode;
import top.csmcool.musicapi.util.ResultUtil;

import java.util.Base64;

@Component
@RequiredArgsConstructor
public class HaloClient {

    private final SystemProperties systemProperties;

    public Users getUserInfo(String username, String password) {
        String encode =  encode((username + ":" + password).getBytes());
        String result2 = HttpRequest.get(systemProperties.getLoginUrl() +
                        "/apis/api.console.halo.run/v1alpha1/users/"
                        + username)
                .header("accept", "*/*")
                .header("Authorization", "Basic "
                        + encode)
                .timeout(5000)//超时，毫秒
                .execute().body();

        JSONObject spec = null;
        try {
            JSONObject json =  JSONUtil.parseObj(result2);
            spec = json.getJSONObject("user").getJSONObject("spec");
        } catch (Exception e) {
            return  null;
        }

        return buildUsers(spec);
    }

    private Users buildUsers(JSONObject spec) {
        Users bean = null;
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, true);  // 如果需要将布尔类型转换为整数，可以用此配置
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            bean = objectMapper.readValue(JSONUtil.toJsonStr(spec), Users.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return bean;
        }

        return bean;
    }

    private String encode(byte[] content) {
        byte[] encode = Base64.getEncoder().encode(content);
        return new String(encode);
    }
}
